package club.banyuan.hrms.servlet;

import club.banyuan.hrms.dao.DepartmentDao;
import club.banyuan.hrms.dao.impl.DepartmentDaoImpl;
import club.banyuan.hrms.domain.Admin;
import club.banyuan.hrms.domain.Department;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@WebServlet(name = "DepartmentListServlet",urlPatterns = "/dept/list")
@Component
public class DepartmentListServlet extends HttpServlet {
    private DepartmentDao departmentDao;

    @Autowired
    public DepartmentListServlet(DepartmentDao departmentDao) {
        this.departmentDao = departmentDao;
    }

    public DepartmentDao getDepartmentDao() {
        return departmentDao;
    }

    public void setDepartmentDao(DepartmentDao departmentDao) {
        this.departmentDao = departmentDao;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        // 获取查询参数
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        Department department = new Department();
        department.setId((id != null) ? Integer.parseInt(id) : null);
        department.setName(name);
        department.setDescription(description);

        if (id != null) {
            departmentDao.updateDepartment(department);
        } else {
            departmentDao.addDepartment(department);
        }

        response.sendRedirect(request.getContextPath() + "/deptManage.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");

        List<Department> departments = departmentDao.getDepartments();

        // 按照接口要求返回数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", departments.size());
        resultMap.put("code", 0);
        resultMap.put("rows", departments);
        response.getWriter().println(JSONObject.toJSONString(resultMap));
    }
}
